<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item label="">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入卡号/名称"
            clearable

            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="listQuery.status" placeholder="状态">
            <el-option
              v-for="item in stats"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="">
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            size="small"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="selections.length == 0"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        show-summary
        :summary-method="getSummaries"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center"> </el-table-column>

        <el-table-column
          v-for="item in tableColumns"
          :key="item.key"
          align="center"
          :label="item.title"
          :prop="item.key"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" width="220px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getCardList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        size="small"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="卡号" prop="code">
          <el-input type="String" v-model="form.code" placeholder="卡号" />
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input
            type="String"
            v-model="form.name"
            placeholder="优惠卡名称"
          />
        </el-form-item>

        <el-form-item label="面值" prop="money">
          <el-input type="String" v-model="form.money" placeholder="面值金额" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="String" v-model="form.remark" placeholder="备注" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="状态" disabled>
            <el-option
              v-for="item in stats"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="default" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="HandleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { pickerOptions } from "@/utils/const";
import { getCards, addCard, updateCard, delCard, delCards } from "@/api/cards";

import Pagination from "@/components/Pagination";

const defaultForm = {
  id: undefined,
  code: null,
  name: null,
  money: null,
  status: 0,
  remark: null,
};

export default {
  name: "Card",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value == null || value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        callback();
      }
    };

    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        code: [{ required: true, message: "请输入卡号", trigger: "blur" }],
        money: [{ required: true, validator: checkMoney, trigger: "blur" }],
      },

      title: "优惠卡",
      datas: [],

      selections: [],

      dialogVisible: false,
      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        name: undefined,
        status: null,
      },

      tableColumns: [
        {
          key: "code",
          title: "卡号",
          width: "140",
        },
        {
          key: "name",
          title: "名称",
        },
        {
          key: "money",
          title: "面值金额",
        },

        {
          key: "remark",
          title: "备注",
        },
        {
          key: "status_name",
          title: "状态",
        },
      ],

      stats: [
        { id: 0, name: "空" },
        { id: 1, name: "已发放" },
      ],
      pickerOptions,
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCardList();
  },
  methods: {
    getCardList() {
      this.listLoading = true;
      getCards(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.datas = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "money") {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          if (column.property === "money") {
            sums[index] += " 元";
          }
        } else {
          return;
        }
      });
      return sums;
    },

    dataFormatter(row, column, cellValue, index) {
      if (column.property === "money") {
        return cellValue && cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getCardList();
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delCard(row.id);

          this.getCardList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("取消删除!");
        });
    },

    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delCards(sel_ids);

          this.getCardList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    // 保存操作
    async HandleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateCard(this.form);
        } else {
          res = await addCard(this.form);
        }

        this.getCardList();

        const { code, money } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>卡号: ${code}</div>
              <div>充值金额: ${money}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-table {
    margin-top: 10px;
    width: 100%;
  }

  .item {
    margin-top: 8px;
  }
}
</style>